package com.zhilianbao.leyaogo.ui.fragment.goodscategory;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.bql.baseadapter.recycleView.QuickRcvAdapter;
import com.bql.fragmentation.anim.DefaultNoAnimator;
import com.bql.fragmentation.anim.FragmentAnimator;
import com.bql.statetypelayout.AnimationStateTypeLayout;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.CategoryApi;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.model.response.category.GoodsInfo;
import com.zhilianbao.leyaogo.model.response.category.SkuEntity;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.activity.MainActivity;
import com.zhilianbao.leyaogo.ui.activity.goodscategory.GoodsActivity;
import com.zhilianbao.leyaogo.ui.adapter.goodscategory.GoodsAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.RefreshAndLoadFragment;
import com.zhilianbao.leyaogo.utils.GoodsSpecPopUtils;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.ShopAnimationUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.okhttputils.request.BaseRequest;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 商品列表fragment
 * Created by gyt on 2016/11/21
 */
public class GoodsListFragment extends RefreshAndLoadFragment<GoodsInfo> {
    private static final String ARG_ID   = "arg_id";
    private static final String ARG_TYPE = "arg_type";
    @BindView(R.id.stateLayout)
    AnimationStateTypeLayout mStateLayout;
    private GoodsAdapter mGoodsAdapter;
    private int          mId;
    public  ImageView    mGoodsIcon;
    private int          mType;
    private GoodsInfo mGoodsInfo;


    public static GoodsListFragment getInstance(int type, int id) {
        Bundle args = new Bundle();
        args.putInt(ARG_TYPE, type);
        args.putInt(ARG_ID, id);
        GoodsListFragment fragment = new GoodsListFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_category_content;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.BUNDLE_GOODS_ID, mList.get(position).getGoodsId());
        bundle.putInt(IntentConfig.BUNDLE_GOODS_SKU_ID, mList.get(position).getGoodsSkuId());
        Utils.startActivity(mActivity, GoodsActivity.class, bundle);
    }

    @Override
    public QuickRcvAdapter<GoodsInfo> getAdapter() {
        return mGoodsAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mActivity);
    }


    @Override
    public boolean canRefresh() {
        return true;
    }

    @Override
    public void onRefresh() {
        loadDataList(1, true);
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        mCurPage = curPage;
        if (mType == 0) {
            getCategoryList(isPullToRefresh);
        } else {
            getActivityGoodsList(isPullToRefresh);
        }

    }

    /**
     * 获取活动/专题商品列表
     *
     * @param isPullToRefresh
     */
    private void getActivityGoodsList(boolean isPullToRefresh) {
        CategoryApi.getActivityGoodsList(mActivity, mId, mCurPage, 20, new CategoryCallback(isPullToRefresh));
    }


    /**
     * 根据类型获取商品列表
     *
     * @param isPullToRefresh
     */
    private void getCategoryList(boolean isPullToRefresh) {
        CategoryApi.getGoodsList(mActivity, Utils.getSupplierId() /*1237*/, mId, mCurPage, 20, new CategoryCallback(isPullToRefresh));
    }


    public class CategoryCallback extends RefreshAndLoadCallback<List<GoodsInfo>> {

        public CategoryCallback(boolean isPullToRefresh) {
            super(isPullToRefresh);
        }

        @Override
        public void onBefore(BaseRequest request) {
            super.onBefore(request);
            if (!isPullToRefresh) {
                ((GoodsCategoryFragment) getParentFragment()).showLoadingView();
                mStateLayout.hideContentView();//正在加载时，隐藏布局，不让其可以下拉刷新
            }
        }

        @Override
        public void errorLeftOrEmptyBtnClick(View v) {
            //                mStateLayout.hideEmptyView();
            mStateLayout.hideErrorView();
            //                mStateLayout.hideContentView();
            loadDataList(1, false);
        }

        @Override
        public boolean isShowLoading() {
            return false;
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            super.onError(call, response, e);
            ((GoodsCategoryFragment) getParentFragment()).hideLoadingView();
        }

        @Override
        public void onResultSuccess(List<GoodsInfo> goodsInfos, @Nullable Response response, LoadingViewCallback callback) {
            ((GoodsCategoryFragment) getParentFragment()).hideLoadingView();
            handleRefreshAndLoadListData(mCurPage, callback, goodsInfos);
        }
    }

    ;


    @Override
    public void onLoadMore() {
        loadDataList(mCurPage, true);
    }

    /**
     * 要加上该方法
     *
     * @return
     */
    @Override
    protected FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultNoAnimator();
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        Bundle args = getArguments();
        if (args == null) {
            return;
        }
        mType = args.getInt(ARG_TYPE);
        mId = args.getInt(ARG_ID);
        mGoodsAdapter = new GoodsAdapter(mActivity, mList, mType);

        mGoodsAdapter.setOnAddToCartClickListener(new GoodsAdapter.OnAddToCartClickListener() {
            @Override
            public void onAddToCartClick(ImageView v, RecyclerView.ViewHolder vh, int position) {
                mGoodsIcon = v;
                mGoodsInfo = mList.get(position);
                if (Utils.isUserLogin(true, LogicCodeBlock.LogicState.AddToCart.value)) {
                    showSpecPop();
                } else {
                    // 没有登录则注册登录回调，
                    XToastUtils.showShortToast(R.string.msg_login_to_add_goods);
                    LogicCodeBlock.create().registerLogicCodeCallback(new LogicCodeBlock.LogicCodeBlockCallback() {
                        @Override
                        public void next(int logicState) {
                            if (logicState == LogicCodeBlock.LogicState.AddToCart.value) {
                                showSpecPop();
                            }
                        }
                    });
                }
            }
        });
    }


    private void showSpecPop() {
        if (Utils.isShowSpePop(mGoodsInfo.getGoodsType(), mGoodsInfo.getGoodsSkuId())) {

            Utils.showSpecPop(mActivity, getView(), 1, mGoodsInfo.getGoodsPic(), mGoodsInfo.getGoodsSkuId(), mGoodsInfo.getSelectedSkuId(), mGoodsInfo.getSku(), mGoodsInfo.getSkuMap(), new GoodsSpecPopUtils.OnPopClickListener() {
                @Override
                public void onAddToCart(View v, int goodsSkuId) {
                    // 设置gooSkuId
                    mGoodsInfo.setGoodsSkuId(goodsSkuId);
                    addToCart();
                    //重置goodsSkuId
                    mGoodsInfo.setGoodsSkuId(0);
                }

                @Override
                public void onSpecSelect(SkuEntity skuEntity) {
                    mGoodsInfo.setSelectedSkuId(skuEntity.getGoodsSkuId());
                }
            });

        } else {// 不是sku商品，或是sku商品但是后台根据sku的类型分类成多个商品返回出来
            addToCart();
        }

    }


    /**
     * 把商品添加到购物车
     */
    private void addToCart() {
        int userId = (int) Utils.getUserLoginInfo().getUserId();
        int goodsId = mGoodsInfo.getGoodsId();
        int supplierId = mGoodsInfo.getSupplierId();
        int shopId = mGoodsInfo.getShopId();
        int goodsSkuId = mGoodsInfo.getGoodsSkuId();


        CategoryApi.addToShoppingCart(mActivity, userId, goodsId, supplierId, shopId, goodsSkuId, 1, 0, new JsonCallback<GoodsStock>(mActivity) {

            @Override
            public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                // 执行飞入购物车的动画
                ShopAnimationUtils.addToShoppingCart(mActivity, 1, mGoodsIcon, ((MainActivity) mActivity).getShopTabView(), ((MainActivity) mActivity).getRlContent(), false, new ShopAnimationUtils.IAnimEndListener() {
                    @Override
                    public void onAnimEnd() {
                        XToastUtils.showShortToast(R.string.msg_add_to_shoppingCart_sucs);
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART));
                    }
                });
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                //                    XToastUtils.showShortToast(R.string.msg_add_to_shoppingCart_failed);
            }
        });
    }

    @Override
    protected void initToolbarHere() {

    }

}
